﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;

using ConstructionBidOnline.DAL;
using ConstructionBidOnline.DAL.dsEmailLayoutTableAdapters;
using ConstructionBidOnline.Common;

namespace ConstructionBidOnline.Biz
{
    /// <summary>
    /// EmailLayout Business Object
    /// </summary>

    public class EmailLayout : BOBase
    {


        #region Construction / Disposal

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected EmailLayout() { }

        #endregion

        #region Public Properties

        #region Instance Properties

        /// <summary>
        /// PKID of the EmailLayout.
        /// </summary>
        public int EmailLayoutID
        {
            get { return _emaillayoutID; }
            set
            {
                if (_emaillayoutID != value)
                {
                    if (OnPropertyChanging("EmailLayoutID", _emaillayoutID, value))
                    {
                        int oldValue = _emaillayoutID;
                        _emaillayoutID = value;

                        OnPropertyChanged("EmailLayoutID", oldValue, value);
                    }
                }
            }
        }  private int _emaillayoutID = -1;


        /// <summary>
        /// Selected EmailCategoryName.
        /// </summary>
        public string EmailCategoryName
        {
            get { return _emailcategoryname; }
            set
            {
                if (_emailcategoryname != value)
                {
                    if (OnPropertyChanging("EmailCategoryName", _emailcategoryname, value))
                    {
                        string oldValue = _emailcategoryname;
                        _emailcategoryname = value;

                        OnPropertyChanged("EmailCategoryName", oldValue, value);
                    }
                }
            }
        }  private string _emailcategoryname = null;



        /// <summary>
        /// Email Subject Line.
        /// </summary>
        public string EmailSubjectLine
        {
            get { return _emailsubjectline; }
            set
            {
                if (_emailsubjectline != value)
                {
                    if (OnPropertyChanging("EmailSubjectLine", _emailsubjectline, value))
                    {
                        string oldValue = _emailsubjectline;
                        _emailsubjectline = value;
                        OnPropertyChanged("EmailSubjectLine", oldValue, value);
                    }
                }
            }
        }  private string _emailsubjectline = null;


        /// <summary>
        /// Email Body Content.
        /// </summary>
        public string EmailBodyContent
        {
            get { return _emailbodycontent; }
            set
            {
                if (_emailbodycontent != value)
                {
                    if (OnPropertyChanging("EmailBodyContent", _emailbodycontent, value))
                    {
                        string oldValue = _emailbodycontent;
                        _emailbodycontent = value;
                        OnPropertyChanged("EmailBodyContent", oldValue, value);
                    }
                }
            }
        }  private string _emailbodycontent = null;


        /// <summary>
        /// Email Layout File.
        /// </summary>
        public string EmailLayoutFile
        {
            get { return _emaillayoutfile; }
            set
            {
                if (_emaillayoutfile != value)
                {
                    if (OnPropertyChanging("EmailLayoutFile", _emaillayoutfile, value))
                    {
                        string oldValue = _emaillayoutfile;
                        _emaillayoutfile = value;
                        OnPropertyChanged("EmailLayoutFile", oldValue, value);
                    }
                }
            }
        }  private string _emaillayoutfile = null;



        /// <summary>
        /// True iff the Admin has made this EmailLayout Active (i.e. to be used in the application).
        /// </summary>
        public bool IsActive
        {
            get { return _isActive; }
            set
            {
                if (_isActive != value)
                {
                    if (OnPropertyChanging("IsActive", _isActive, value))
                    {
                        bool oldValue = _isActive;
                        _isActive = value;
                        OnPropertyChanged("IsActive", oldValue, value);
                    }
                }
            }
        }  private bool _isActive = false;

        #endregion

        #endregion

        #region Public Methods

        #region CreateNew

        /// <summary>
        /// Creates a new, empty EmailLayout object.
        /// </summary>
        public static EmailLayout CreateNew()
        {
            EmailLayout obj = new EmailLayout();

            // Switch state to Added prior to initializing property values.
            obj.ObjState = ObjectState.Added;

            obj.IsActive = true;
            return (obj);
        }


        [MethodImpl(MethodImplOptions.Synchronized)]
        public static EmailLayout CreateNew(EmailLayoutCollection collection)
        {
            EmailLayout obj = CreateNew();

            // Get next/unique ID for the new object.
            int minVal = 0;
            foreach (EmailLayout EmailLayout in collection)
            {
                if (EmailLayout.EmailLayoutID < minVal)
                    minVal = EmailLayout.EmailLayoutID;
            }
            obj.EmailLayoutID = --minVal;
            collection.Add(obj);

            return (obj);
        }

        #endregion

        #region GetAllEmailLayouts

        /// <summary>
        /// Returns a collection of all EmailLayout.
        /// </summary>
        public static EmailLayoutCollection GetAllEmailLayouts()
        {
            EmailLayoutTableAdapter adapter = new EmailLayoutTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsEmailLayout.EmailLayoutDataTable tbl = adapter.GetData(null);

            EmailLayoutCollection list = new EmailLayoutCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsEmailLayout.EmailLayoutRow row in tbl.Rows)
                {
                    EmailLayout emaillayout = new EmailLayout();
                    RelationalToObject(emaillayout, row);
                    list.Add(emaillayout);
                }
            }

            return (list);
        }

        #endregion

        #region GetEmailLayoutByID

        /// <summary>
        /// Returns an EmailLayout object for the specified 'EmailLayoutID' or null if no EmailLayout with the specified parameter(s) exists.
        /// </summary>
        public static EmailLayout GetEmailLayoutByID(int emaillayoutid)
        {
            EmailLayoutTableAdapter adapter = new EmailLayoutTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsEmailLayout.EmailLayoutDataTable tbl = adapter.GetData(emaillayoutid);

            if (tbl.Rows.Count == 1)
            {
                EmailLayout el = new EmailLayout();
                RelationalToObject(el, tbl.Rows[0]);
                return (el);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'EmailLayout' returned more than one record.");

            return (null);
        }

        #endregion

        #region Update

        /// <summary>
        /// Updates the specified EmailLayout.
        /// </summary>
        public static void Update(EmailLayout obj)
        {
            bool updateEmailLayout = false;

            // Do not update invalid objects.
            if (!obj.Validate())
            {
                StringBuilder sb = new StringBuilder(2048);
                sb.Append("The object being updated has one or more invalid properties; the Update() operation for this object has been cancelled.\nError(s):");
                foreach (ValidationError err in obj.Errors)
                    sb.Append("\n* " + err.Element + ": " + err.Message);

                throw new InvalidObjectException(sb.ToString());
            }
            else
            {
                updateEmailLayout = (obj.ObjState != ObjectState.Unchanged);

                if (!updateEmailLayout)
                    return;
            }

            ObjectState originalObjectState = obj.ObjState;

            dsEmailLayout.EmailLayoutDataTable tbl = null;
            if (updateEmailLayout)
            {

                EmailLayoutTableAdapter adapter = new EmailLayoutTableAdapter();
                adapter.Connection = AppSettings.GetDbConn();


                tbl = new dsEmailLayout.EmailLayoutDataTable();
                dsEmailLayout.EmailLayoutRow row = tbl.NewEmailLayoutRow();
                ObjectToRelational(obj, tbl, row);

                adapter.Update(tbl);

                if (originalObjectState == ObjectState.Deleted)
                    obj = null;
                else RelationalToObject(obj, tbl.Rows[0]);
            }
        }


        #endregion

        #region Validate

        /// <summary>
        /// Validates the object based on its properties at the time of the call; updates the Errors property.
        /// </summary>
        public override bool Validate()
        {
            Errors.Clear();

            if (ObjState == ObjectState.Unchanged)
            {
                // By definition, unchanged objects are valid.
                return (true);
            }
            else if (ObjState == ObjectState.Uninitialized)
            {
                Errors.Add(new ValidationError("object", "Object is uninitialized.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else if ((ObjState == ObjectState.Deleted) && (EmailLayoutID <= 0))
            {
                // Deleted items must have 'real' (i.e. non-negative, non-zero) key(s) to be valid.
                Errors.Add(new ValidationError("EmailLayoutID", "Deleted object has an invalid PKID.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else  // ObjState == Added | Modified
            {

                // SubCategoryName.
                if ((EmailSubjectLine == null) || (EmailSubjectLine.Trim().Length == 0))
                {
                    Errors.Add(new ValidationError("EmailSubjectLine", "EmailSubjectLine is required.", ValidationError.Severity.Error));
                }
                else if (ObjState == ObjectState.Added)
                {

                }

            }

            return (Errors.Count == 0);
        }

        #endregion

        #region ToString

        /// <summary>
        /// User-friendly string represetation of this object.
        /// </summary>
        public override string ToString()
        {
            return (String.Format("EmailLayout: ELID={0}, EmailSubjectLine={1}, {2}", EmailLayoutID, EmailSubjectLine, EmailBodyContent));
        }

        #endregion

        #endregion

        #region Privates


        #endregion

    }

    /// <summary>
    /// Collection of 0 or more EmailLayout objects.
    /// </summary>

    public class EmailLayoutCollection : List<EmailLayout>
    {
        #region Types

        public class UserComparer : IComparer<EmailLayout>
        {
            public int Compare(EmailLayout el1, EmailLayout el2)
            {
                return (String.Compare(el1.EmailSubjectLine, el2.EmailSubjectLine));
            }
        }

        #endregion

        #region Public Methods

        #region FindByEmailLayoutID

        public EmailLayout FindByEmailLayoutID(int EmailLayoutID)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].EmailLayoutID == EmailLayoutID)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #region FindByEmailLayout

        /// <summary>
        /// Case insensitve compare.
        /// </summary>
        public EmailLayout FindByEmailLayout(string emailsubjectline)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].EmailSubjectLine == emailsubjectline)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #endregion

    }
}
